
<script setup>
import { ref,onMounted,computed } from 'vue';
import { queryClazzBySubjectApi } from '@/api/student';
import { ElMessage } from 'element-plus';
import { updateStudentApi,queryStuApi } from '@/api/stu';
import { queryClazzApi } from '@/api/report';
import { queryAllClazzApi } from '@/api/clazz';
import { useRouter } from 'vue-router';

const router = useRouter();

const statusTypeMap = {
  '未开课': 'warning',
  '已开课': 'success',
  '已结课': 'info'
};

const infoItems = {
    room: { label: '教室' },
    masterName: { label: '班主任' },
    beginDate: { label: '开课时间' },
    endDate: { label: '结课时间' }
};

// 课程数据
const courses = ref([

]);

const getStatusClass = (status) => ({
  'status-not-started': status === '未开课',
  'status-in-progress': status === '已开课',
  'status-completed': status === '已结课'
});

const studentInfo=ref({
    // name: '',
    // no: '',
    // clazzName:'',
    // room:'',
    // beginDate:'',
    // endDate:'',
    // violationCount:'', 
    // violationScore:'',
    // clazzId:''
});

const getStu= async ()=>{
  let Student=JSON.parse(localStorage.getItem('Student'));
  let id=Student.id;
  const result=await queryStuApi(id);
  if(result.code){
    studentInfo.value=result.data;
  }
}

const hasSelected=computed(()=>{
  if(localStorage.getItem('hasSelected')){
    return true;
  }
  return false;
});


const handleSelect = async (course) => {
  if (course.isSelected) return; // 防止重复提交
  if(studentInfo.value){
    studentInfo.value.clazzId=course.id;
    studentInfo.value.violationCount=0;
    studentInfo.value.violationScore=0;
    const result1=await updateStudentApi(studentInfo.value);
    if(result1.code){
      ElMessage.success('选课成功');
      // 更新全局选课状态
      courses.value = courses.value.map(c => ({
        ...c,
        isSelected: c.id === course.id
      }));
      searchClazzStu().then(()=>{
        search();
      });
    }else{
      ElMessage.error(result1.msg);
    }
  }
}


const clazzList=ref([]);
const dataList=ref([]);
const searchClazzStu= async ()=>{
  const result=await queryClazzApi();
  if(result.code){
    clazzList.value=result.data.clazzList;
    dataList.value=result.data.dataList;
  }
};

const Cla=ref([
    {name:'Java',value:1},{name:'前端',value:2},
    {name:'大数据',value:3},{name:'Python',value:4},
    {name:'Go',value:5},{name:'嵌入式',value:6}
]);

const search= async ()=>{
    const result=await queryClazzBySubjectApi(Cla.value[2].value);
    if(result.code){
         // 使用 map 创建新对象，添加响应式 flag 属性
        courses.value = result.data.map(course => ({
          ...course, // 保留原有属性
          isSelected: course.id === studentInfo.value?.clazzId
        }));
        const LocalclazzList=clazzList.value;
        courses.value.forEach( 
          (course) => {
            for(let i=0;i<LocalclazzList.length;i++){
              if(course.name===LocalclazzList[i]){
                course.currentClassSize=dataList.value[i];
              }
            }
          }
        );
    }
}

onMounted(()=>{
    searchClazzStu().then(()=>{
        search();
    });
    getStu();
});

function getCurrentDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}



</script>


<template>
    <div class="course-container">
      <!-- 顶部标题 -->
      <div class="header-content">
            <h1 class="title-gradient">{{Cla[2].name}}课程方向</h1>
            <br>
        </div>
  
      <!-- 课程卡片容器 -->
      <div class="course-grid">
        <transition-group name="card-list">
          <el-card 
            v-for="(course, index) in courses" 
            :key="course.name"
            class="course-card"
            :class="getStatusClass(course.status)"
            shadow="hover"
          >
            <div class="card-header">
              <span class="class-name">{{ course.name }}</span>
              <el-tag :type="statusTypeMap[course.status]" effect="dark">
                {{ course.status }}
              </el-tag>
            </div>
            
            <el-divider class="custom-divider" />
  
            <div class="course-info">
              <div v-for="(item, key) in infoItems" :key="key" class="info-item">
                <span class="label">{{ item.label }}：</span>
                <span class="value">{{ course[key] || item.default }}</span>
              </div>
            </div>
  
            <el-divider class="custom-divider" />
  
            <div class="class-stats">
              <div class="progress-container">
                <span>已选人数：{{ course.currentClassSize }} / {{ 40 }}</span>
                <el-progress 
                  :percentage="(course.currentClassSize / 40) * 100" 
                  :status="course.status === '已结课' ? 'exception' : 'success'"
                  :show-text="false"
                />
              </div>
              <el-button 
                :type="course.isSelected ? 'danger' : 'primary'" 
                :disabled="course.status !== '未开课' || hasSelected"
                class="select-btn"
                @click="handleSelect(course)"
              >
              {{ course.isSelected ? '已选课程' : '立即选课' }}
              </el-button>
            </div>
          </el-card>
        </transition-group>
      </div>
    </div>
  </template>
  
  
  <style scoped>
  .course-container {
    padding: 2rem;
    background: #f8f9fa;
  }
  
  .page-header {
    margin-bottom: 2rem;
  }
  
  .title-gradient {
    background: linear-gradient(45deg, #0093E9, #80D0C7);
    -webkit-background-clip: text; /* 兼容WebKit内核浏览器 */
    background-clip: text; /* 标准属性 */
    color: transparent;
    font-size: 2.5rem;
  }
  
  
  .course-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 1.5rem;
  }
  
  .course-card {
    transition: all 0.3s ease;
    border-radius: 12px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.5rem 0;
  }
  
  .class-name {
    font-weight: 600;
    color: #2c3e50;
  }
  
  .custom-divider {
    margin: 1rem 0;
  }
  
  .course-info {
    display: grid;
    gap: 0.8rem;
    padding: 0.5rem 0;
  }
  
  .info-item {
    display: flex;
    justify-content: space-between;
    font-size: 0.95rem;
  }
  
  .label {
    color: #7f8c8d;
    font-weight: 500;
  }
  
  .value {
    color: #2c3e50;
  }
  
  .class-stats {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 1rem;
  }
  
  .progress-container {
    flex: 1;
    margin-right: 1rem;
  }
  
  .select-btn {
    transition: transform 0.2s ease;
  }
  
  .select-btn:hover {
    transform: translateY(-2px);
  }
  
  /* 状态指示条 */
  .course-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    border-radius: 4px 4px 0 0;
  }
  
  .status-not-started::before { background: #e6a23c; }
  .status-in-progress::before { background: #67c23a; }
  .status-completed::before { background: #909399; }
  
  /* 入场动画 */
  .card-list-enter-active {
    transition: all 0.5s ease;
  }
  .card-list-enter-from {
    opacity: 0;
    transform: translateY(30px);
  }
  </style>